<?php
/**
 * ApiBaseController.php
 * @author zohnの梦
 * @email  1171672036@qq.com
 * @date   2021/1/9
 */

namespace app\api\controller;


use app\BaseController;
use app\common\exception\RequestException;
use think\facade\Config;
use think\facade\Request;

class ApiBaseController extends BaseController
{
    /**
     * Token
     * @var string
     */
    public $token;

    /**
     * 用户 id
     * @var int
     */
    protected $user_id;

    /**
     * 构造方法
     */
    public function __construct()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit;
        }

        $this->checkToken();
    }

    /**
     * 检查 token
     * @return array
     */
    protected function checkToken()
    {
        $token = $this->token = Request::header(Config::get('api.token_key'));
        $key   = Config::get('api.domain');
        if (empty($token)) throw new RequestException(404, 'token 不存在');

        $decrypt = decrypt($token, $key);
        if (empty($decrypt)) throw new RequestException(401, 'token 错误');

        $data = json_decode($decrypt, true);
        if ($data['expire_time'] < time()) throw new RequestException(401, 'token 已过期');

        $this->user_id = $data['user_id'];

        return $data;
    }

    /**
     * 创建 token
     * @param int $user_id 用户 id
     * @param int $expire_time 过期时间
     * @return string
     */
    public function createToken($user_id, $expire_time = 86400)
    {
        $key  = Config::get('api.domain');
        $data = [
            'user_id'     => $user_id,
            'create_time' => time(),
            'expire_time' => empty($expire_time) ? 0 : time() + $expire_time
        ];

        $token = encrypt(json_encode($data), $key);

        return $token;
    }

}